<template>
  <div class="container user-list" v-loading="loadinggroup">
    <div class="handle-box">
      <el-input v-model="querygroup.groupname" placeholder="用户组组名称" class="handle-input mr10"></el-input>
      <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>

      <el-button type="success" :icon="Plus" @click="addUserGroup">新增用户组</el-button>
    </div>

    <el-row>
      <el-table :data="usersgroup.items" border class="table" :row-key="row => row.id"
                @selection-change="handleSelectionChange" table-layout="auto">
        <el-table-column type="selection" width="38"/>
        <el-table-column prop="groupname" label="组名称"/>
        <el-table-column label="状态" width="80">
          <template #default="scopegroup">
            <el-tag v-if="scopegroup.row.status" type="success">正常</el-tag>
            <el-tag type="danger" v-else>停用</el-tag>
          </template>
        </el-table-column>
<!-- 
        <el-table-column label="聊天角色">
          <template #default="scopegroup">
            <el-select
              v-model="scopegroup.row.chat_roles"
              multiple
              collapse-tags
              :max-collapse-tags="2"
              :filterable="true"
              placeholder="聊天角色"
              >
              <template v-for="item in roles" :key="item">
                <el-option
                  v-if="isItemInArray(item.key, scopegroup.row.chat_roles)"
                  :key="item.key"
                  :label="item.name"
                  :value="item.key"
                  :disabled="true"
                />
              </template>
              
            </el-select>
          </template>
        </el-table-column> -->

        <!-- <el-table-column label="聊天模型">
          <template #default="scopegroup">
            <el-select
              v-model="scopegroup.row.chat_models"
              multiple
              collapse-tags
              :max-collapse-tags="2"
              :filterable="true"
              placeholder="聊天模型"
              >
              <template v-for="item in models" :key="item">
                <el-option
                  v-if="isItemInArray(item.id, scopegroup.row.chat_models)"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  :disabled="true"
                />
              </template>
              
            </el-select>
          </template>
        </el-table-column> -->

        <el-table-column label="用户">
          <template #default="scopegroup">
            <el-select-v2
              v-model="scopegroup.row.chat_users.usersid"
              :options="scopegroup.row.chat_users.options"
              placeholder="暂无绑定"
              multiple
              filterable
              clearable
              collapse-tags
              :max-collapse-tags="2"
            />
          </template>
        </el-table-column>

        <el-table-column label="用户组过期时间">
          <template #default="scopegroup">
            <span v-if="scopegroup.row['user_expired_time']">{{ dateFormat(scopegroup.row['user_expired_time']) }}</span>
            <el-tag v-else>长期有效</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="创建时间">
          <template #default="scopegroup">
            <span>{{ dateFormat(scopegroup.row['created_at']) }}</span>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="150">
          <template #default="scopegroup">
            <el-button-group class="ml-2">
              <el-button size="small" type="primary" @click="userGroupEdit(scopegroup.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="removeUser(scopegroup.row)">删除</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination v-if="usersgroup.total > 0"
                       background
                       layout="total, prev, pager, next"
                       v-model:current-page="usersgroup.page"
                       v-model:page-size="usersgroup.page_size"
                       :total="usersgroup.total"
                       @current-change="fetchUserGroupList(usersgroup.page, usersgroup.page_size)"
        />

      </div>
    </el-row>

    <el-dialog
        v-model="showUserGroupEditDialog"
        :title="title"
        :close-on-click-modal="false"
        width="50%"
    >
      <el-form :model="usergruop" label-width="100px" ref="usergroupEditFormRef" :rules="rulesgroup">
        <el-form-item label="组名称：" prop="groupname">
          <el-input v-model="usergruop.groupname" autocomplete="off"/>
        </el-form-item>

        <el-form-item label="有效期：" prop="user_expired_time">
          <el-date-picker
              v-model="usergruop.user_expired_time"
              type="datetime"
              placeholder="选择日期"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :disabled-date="disabledDate"
          />
        </el-form-item>

        <el-form-item label="聊天角色" prop="chat_roles">
          <el-select
              v-model="usergruop.chat_roles"
              multiple
              :filterable="true"
              placeholder="选择聊天角色，多选"
          >
            <el-option
                v-for="item in roles"
                :key="item.key"
                :label="item.name"
                :value="item.key"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="模型权限" prop="chat_models">
          <el-select
              v-model="usergruop.chat_models"
              multiple
              :filterable="true"
              placeholder="选择AI模型，多选"
          >
            <el-option
                v-for="item in models"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="绑定用户" prop="chat_users">
          <el-select-v2
            v-model="usergruop.chat_users.usersid"
            multiple
            clearable
            filterable
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="3"
            :options="chat_users_options"
            :props="chat_users_props"
            placeholder="Please enter a keyword"
          />
        </el-form-item>


        <el-form-item label="启用状态">
          <el-switch v-model="usergruop.status"/>
        </el-form-item>
      </el-form>

      <template #footer>
            <span class="dialog-footer">
              <el-button @click="showUserGroupEditDialog = false">取消</el-button>
              <el-button type="primary" @click="saveUser">提交</el-button>
            </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import {httpGet, httpPost} from "@/utils/http";
import {ElMessage, ElMessageBox} from "element-plus";
import {dateFormat, disabledDate, removeArrayItem} from "@/utils/libs";
import {Plus, Search} from "@element-plus/icons-vue";

// 变量定义
const usersgroup = ref({page: 1, page_size: 15, items: []})
const querygroup = ref({groupname: '', page: 1, page_size: 15})
const queryuser = ref({username: '', page: 1, page_size: 1000})

const title = ref('添加用户组')
const addgroup = ref(true)
const usergruop = ref({
  chat_roles: [], 
  chat_models: [],
  chat_users: {
    'usersid': []
  }
})
const roles = ref([])
const models = ref([])
const showUserGroupEditDialog = ref(false)
const rulesgroup = reactive({
  groupname: [{required: true, message: '请输入名称', trigger: 'blur',}],
  chat_roles: [{required: true, message: '请选择聊天角色', trigger: 'change'}],
  chat_models: [{required: true, message: '请选择AI模型', trigger: 'change'}],
})
const loadinggroup = ref(true)

const usergroupEditFormRef = ref(null)

const chat_users_options = ref([])
const chat_users_props = {
  label: 'username',
  value: 'id',
}

onMounted(() => {
  fetchUserGroupList(usersgroup.value.page, usersgroup.value.page_size)
  fetchUserList(1, 1000)
  // 获取角色列表
  httpGet('/api/admin/role/list').then((res) => {
    roles.value = res.data;
  }).catch(() => {
    ElMessage.error("获取聊天角色失败");
  })

  httpGet('/api/admin/model/list').then(res => {
    models.value = res.data
  }).catch(e => {
    ElMessage.error("获取模型失败：" + e.message)
  })
})

const fetchUserGroupList = function (page, pageSize) {
  querygroup.value.page = page
  querygroup.value.page_size = pageSize
  httpGet('/api/admin/usergroup/list', querygroup.value).then((res) => {
    if (res.data) {
      // 初始化数据
      const arr = res.data.items;
      for (let i = 0; i < arr.length; i++) {
        arr[i].user_expired_time = dateFormat(arr[i].user_expired_time)
      }
      usersgroup.value.items = arr
      usersgroup.value.total = res.data.total
      usersgroup.value.page = res.data.page
      usergruop.value.page_size = res.data.page_size
    }
    loadinggroup.value = false
  }).catch(() => {
    ElMessage.error('加载用户组列表失败')
  })
}

const fetchUserList = function (page, pageSize) {
  queryuser.value.page = page
  queryuser.value.page_size = pageSize
  httpGet('/api/admin/user/list', queryuser.value).then((res) => {
    if (res.data) {
      // 初始化数据
      chat_users_options.value = res.data.items
    }
    loadinggroup.value = false
  }).catch(() => {
    ElMessage.error('加载用户组列表失败')
  })
}

const handleSearch = () => {
  fetchUserGroupList(usersgroup.value.page, usersgroup.value.page_size)
}

const isItemInArray = function (keyname, chatroles) {
  // console.log(keyname, chatroles, "dsadsa")
  if (chatroles.includes(keyname)) {
    return true
  } else {
    return false
  }
}

// const remoteMethod = (query_search) => {
//   // console.log(query, 'dsadas')
//   if (query_search !== '') {
//     loadinggroup.value = true
//     queryuser.value.username = query_search
    
//     httpGet('/api/admin/user/list', queryuser.value).then((res) => {
//       if (res.data) {
//         // 初始化数据
//         chat_users_options.value = res.data.items
//       }
//       loadinggroup.value = false
//     }).catch(() => {
//       ElMessage.error('加载用户列表失败')
//     })

//   } else {
//     chat_users_options.value = []
//   }
// }

// 删除用户组
const removeUser = function (usergruop) {
  ElMessageBox.confirm(
      '此操作将会永久删除用户组信息和聊天记录，确认操作吗?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    httpGet('/api/admin/usergroup/remove', {id: usergruop.id}).then(() => {
      ElMessage.success('操作成功！')
      // console.log(usersgroup.value.items, 'sssss')
      usersgroup.value.items = removeArrayItem(usersgroup.value.items, usergruop, function (v1, v2) {
        return v1.id === v2.id
      })
      // console.log(usersgroup.value.items, 'ccccc')
    }).catch((e) => {
      ElMessage.error('操作失败，' + e.message)
    })
  }).catch(() => {
    ElMessage.info('操作被取消')
  })

}

const userGroupEdit = function (row) {
  usergruop.value = row
  title.value = '编辑用户组'
  showUserGroupEditDialog.value = true
  addgroup.value = false

  // console.log(usergruop.value)
}

const addUserGroup = () => {
  usergruop.value = {
    chat_users: {
      'usersid': []
    }
  }
  title.value = '添加用户组'
  showUserGroupEditDialog.value = true
  addgroup.value = true
}

const saveUser = function () {
  usergroupEditFormRef.value.validate((valid) => {
    if (valid) {
      showUserGroupEditDialog.value = false
      // console.log(user.value, 'adsadsa')
      const copiedDict = JSON.parse(JSON.stringify(usergruop.value))
      delete copiedDict.chat_users.options
      delete copiedDict.created_at
      delete copiedDict.updated_at
      // console.log(copiedDict, 'dasdasdas')
      httpPost('/api/admin/usergroup/save', copiedDict).then((res) => {
        ElMessage.success('操作成功！')
        if (addgroup.value) {
          // console.log(res.data, 'dsadsadsadsaas')
          usersgroup.value.items.push(res.data)
        }
        // console.log(users.value.items, 'wcccccc')
      }).catch((e) => {
        ElMessage.error('操作失败，' + e.message)
      })
    } else {
      return false
    }
  })
}

const handleSelectionChange = function (rows) {
  console.log(rows)
}

</script>

<style lang="stylus" scoped>
.user-list {

  .handle-box {
    margin-bottom 20px
    .handle-input {
      max-width 150px;
      margin-right 10px;
    }
  }

  .table {
    width 100%
  }

  .opt-box {
    padding-bottom: 10px;

    .el-icon {
      margin-right: 5px;
    }
  }

  .pagination {
    padding 20px 0
    display flex
  }

  .el-select {
    width: 100%
  }

}
</style>